<template>
    <div class="___quill-editor">
        <quill-editor v-model="value" :options="editorOption" @change="editorChage" ref="QuillEditor" />
        <el-upload
            v-show="false"
            class="avatar-uploader"
            :action="`${fileApiUrl.uploadFile}${$utils.isNotEmpty(bizPath) ? '?bizPath=' + bizPath : ''}`"
            :headers="{token: token,account_set_sid:account_set_sid }"
            list-type="picture-card"
            :on-success="handleSuccess"
        ></el-upload>
    </div>
</template>

<script>
    import "quill/dist/quill.core.css";
    import "quill/dist/quill.snow.css";
    import "quill/dist/quill.bubble.css";
    import { quillEditor, Quill } from "vue-quill-editor";
    import store from '@/store';
    import '@common/assets/js/image-paste.min.js';
    import fileApi from "@common/api/fileApi";

    export class ImagePaste {
        constructor (quill, config = {}) {
            this.quill = quill;
            this.config = config;
            quill.root.addEventListener('paste', this.handlePaste, false)
        }

        handlePaste = (e) => {
            let clipboardData = e.clipboardData;
            let items, item, types;
            if (!clipboardData) return;
            items = clipboardData.items;
            if (!items) return;
            item = items[0];
            types = clipboardData.types || [];
            for (let i = 0; i < types.length; i++) {
                if (types[i] === 'Files') {
                    item = items[i];
                    break;
                }
            }
            if (item && item.kind === 'file' && item.type.match(/^image\//i)) {
                e.preventDefault();
                const file = item.getAsFile();
                const { addImageBlob } = this.config;
                if (addImageBlob && {}.toString.call(addImageBlob) === '[object Function]') {
                    addImageBlob(file, this.insertImg)
                } else {
                    this.toBase64(file)
                }
            }
        };

        toBase64 = (file) => {
            const reader = new FileReader();
            reader.onload = (e) => {
                this.insertImg(e.target.result)
            };
            reader.readAsDataURL(file)
        };

        insertImg = (url) => {
            const index = (this.quill.getSelection() || {}).index || this.quill.getLength() - 1;
            this.quill.insertEmbed(index, 'image', url, 'user');
            setTimeout(() => {
                this.quill.setSelection(index + 1)
            }, 0)
        }
    }
    Quill.register('modules/imagePaste', ImagePaste);

    export default {
        props: {
            editorValue: {
                type: String
            },
            bizPath: String,
        },
        components: {
            quillEditor
        },
        data () {
            let $this = this;
            return {
                fileApiUrl: fileApi.url,
                token: store.state.accessToken.token,
                account_set_sid:this.$utils.getAccountSetSid(),
                value: "",
                // content_file_id: '',
                fileUrl: fileApi.url.getFile,
                editorOption: {
                    modules: {
                        imagePaste: {
                            addImageBlob: function (blob, callback) {
                                let formData = new FormData();
                                formData.append('file', blob);
                                if ($this.$utils.isNotEmpty($this.bizPath)) {
                                    formData.append("bizPath", $this.bizPath);
                                }
                                fileApi.uploadFormData(formData, res => {
                                    if (res.data.oss_url){
                                        callback(res.data.oss_url);
                                    }else{
                                        let imageUrl = fileApi.url.getFile +$this.account_set_sid+'/'+res.data.sid;
                                        callback(imageUrl)
                                    }
                                });
                            }
                        },
                        toolbar: {
                            container: [
                                ["bold", "italic", "underline", "strike"], // toggled buttons
                                ["blockquote", "code-block"],

                                [{ header: 1 }, { header: 2 }], // custom button values
                                [{ list: "ordered" }, { list: "bullet" }],
                                [{ script: "sub" }, { script: "super" }], // superscript/subscript
                                [{ indent: "-1" }, { indent: "+1" }], // outdent/indent
                                [{ direction: "rtl" }], // text direction

                                [{ size: ["small", false, "large", "huge"] }], // custom dropdown
                                [{ header: [1, 2, 3, 4, 5, 6, false] }],

                                [{ color: [] }, { background: [] }], // dropdown with defaults from theme
                                [{ font: [] }],
                                [{ align: [] }],
                                ["link", "image", "video"],
                                ["clean"] // remove formatting button
                            ], // 工具栏
                            handlers: {
                                image: function(value) {
                                    if (value) {
                                        document.querySelector(".___quill-editor .el-upload").click();
                                    } else {
                                        this.quill.format("image", false);
                                    }
                                }
                            }
                        }
                    }
                }
            };
        },
        watch: {
            editorValue() {
                this.value = this.editorValue;
            }
        },
        mounted() {
            this.value = this.editorValue;
        },
        methods: {
            handleSuccess(res) {
                // 获取富文本组件实例
                let quill = this.$refs.QuillEditor.quill;
                // 如果上传成功
                if (res) {
                    // 获取光标所在位置
                    let length = quill.getSelection().index;
                    // 插入图片，res为服务器返回的图片链接地址
                    quill.insertEmbed(length, "image", this.fileUrl +this.account_set_sid+"/"+res.data.sid);
                    // quill.insertEmbed(length, "image", res.data.file_path);
                    // 调整光标到最后
                    quill.setSelection(length + 1);
                } else {
                    // 提示信息，需引入Message
                    Message.error("图片插入失败");
                }
            },
            editorChage: function () {
                // this.$parent.setEditorValue(this.value);
                this.$emit("setEditorValue", this.value);
            }
        }
    }

</script>


<style lang="less" scoped>
.___quill-editor {
    width: 100%;
    height: 100%;
    --ql-container-height: 45px;

    .quill-editor {
        width: 100%;
        height: 100%;

        /deep/.ql-container {
            height: calc(100% - var(--ql-container-height));
        }
    }
}
</style>
